﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;

/// <summary>
/// Engine 的摘要说明 
/// this class is responsible for main logic, which includes below functions:
/// 1) Initialize 
/// 2) process user event
/// 3) communicate with each modules
/// 4) use session state to save current state.
/// </summary>
public enum UserStatus{
    UserStatus_Login,
    Userstatus_UserInforList,
    UserStatus_Null,
}

public enum UserGroup{
    Admin,
    Assitant,
    Safety,
    Lead,
    ViceLead,
    Director,
    Manager,
    Staff,
    Guest,
}

public enum ButtonCmd{
    SelfScore,
    MemberScores,
    MemberList,
    DivisionList,
}

public class Engine
{

    public Engine(Page MainPage)
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
        m_MainPage = MainPage;
        m_ButtonCmdList["自评分"] = ButtonCmd.SelfScore;
        m_ButtonCmdList["部门评分"] = ButtonCmd.MemberScores;
        m_ButtonCmdList["部门列表"] = ButtonCmd.DivisionList;
        m_ButtonCmdList["人员名单"] = ButtonCmd.MemberList;
    }
   
    //Page send message to engine
    public void SendMessage()
    {

    }
    
    public int GetCurSerialNum()
    {
        string userName = (string)m_MainPage.Session[m_Usnkey];
        return int.Parse(userName);
    }

    public UserGroup GetCurUserGroup()
    {
        if (m_MainPage.Session[m_Usgkey] == null)
        {
            m_MainPage.Session[m_Usgkey] = UserGroup.Guest;
        }
        return (UserGroup)m_MainPage.Session[m_Usgkey];
        
    }

    public UserStatus GetCurUserState()
    {
        if (m_MainPage.Session[m_Usskey] == null)
        {
            m_MainPage.Session[m_Usskey] = UserStatus.UserStatus_Login;
        }
        return (UserStatus)m_MainPage.Session[m_Usskey];;
    }

    //Content control name. Content control will decide by current navigation
    //The content in control will be depend on the username, user position, time  
    public string GetContentCtrlName()
    {
        //Get current content control bind with current navigate buttons
        string CtrlName = null;
  
        string CurNavName = null;
        if(m_MainPage.Session[m_NavKey] == null)
        {
            CurNavName = ((NavButton)m_NavButtons[0]).Name;
            m_MainPage.Session[m_NavKey] = CurNavName;
            CtrlName = ((NavButton)m_NavButtons[0]).ContentCtrlName;
        }
        else
        {
            CurNavName = (string)m_MainPage.Session[m_NavKey];
            foreach(NavButton o in m_NavButtons)
            {
                if(CurNavName == o.Name)
                {
                    CtrlName = o.ContentCtrlName;
                    break;
                }
            }
        }
   
        return CtrlName;
    }
    
    public void GetContentTitle()
    {
        //
    }
    
    public ButtonCmd GetFirstButtonCmd()
    {
        //Get first button 
        string BtnName = ((LinkButton)m_CtrlButtons[0]).Text;
        ButtonCmd CmdName = GetCmdByButtonName(BtnName); 
        return CmdName;
    }

    private ButtonCmd GetCmdByButtonName(string ButtonName)
    {
        return (ButtonCmd)m_ButtonCmdList[ButtonName];
    }

    //Trigger page to load SelfScore content
    public void NavButton_Click(object sender, EventArgs e)
    {
        //Reload the pages
        string ButtonName = ((LinkButton)sender).Text;
       // ButtonCmd CmdName = GetCmdByButtonName(ButtonName);
        m_MainPage.Response.Redirect("default.aspx?NavButton=" + ButtonName);

    }


    private void CreateNavButtons(string[,] BtnInfoList)
    {
        for(int i = 0; i < BtnInfoList.Length / 3; i++)
        {
            //if the button belongs to current phase
            int CurrentPhase = Utility.GetCurrentPhase();
            if (CurrentPhase.ToString() == BtnInfoList[i,2].ToString()
              ||BtnInfoList[i,2] == "0"
              ||BtnInfoList[i,2] == "5")
            {
                LinkButton newLb = new LinkButton();
                newLb.Text = BtnInfoList[i,0];
                newLb.Click += new EventHandler(NavButton_Click);
                NavButton curNavButton = new NavButton(newLb, BtnInfoList[i, 0], BtnInfoList[i, 1]);

                m_NavButtons.Add(curNavButton);
            }
        }
    }

    //Get navigation control
    public ArrayList GetNavigationControl()
    {
        UserGroup CurUserGroup = GetCurUserGroup();
        m_NavButtons.Clear();
        m_CtrlButtons.Clear();
        //Dynamic create nav buttons based user group, it's a time comsuming method
        switch (CurUserGroup)
        {
            case UserGroup.Guest:
                //without any navigation button

                break;
            case UserGroup.Staff:
                //without any navigation button
                {

                    CreateNavButtons(Layout.Nav_Staff);
                    
                }
                break;
            case UserGroup.Lead:
                //with self score and his staff score list buttons
                {
                    CreateNavButtons(Layout.Nav_Lead);
                }
                
                break;
            case UserGroup.ViceLead:
                {
                    CreateNavButtons(Layout.Nav_ViceLead);
                }
                break;
            case UserGroup.Manager:
                //with self score, his leads score list and division list
                {
                    CreateNavButtons(Layout.Nav_Manager);
                
                }
                break;
            case UserGroup.Director:
                //with self score, his leads score list and division list
                {
                    CreateNavButtons(Layout.Nav_Director);

                }
                break;
            case UserGroup.Admin:
                //with division management, staff management buttons 
                {
                    CreateNavButtons(Layout.Nav_Admin);
                
                }
                break;
            case UserGroup.Assitant:
                //with division management, staff management buttons 
                {
                    CreateNavButtons(Layout.Nav_Assitant);

                }
                break;
            case UserGroup.Safety:
                //with division management, staff management buttons 
                {
                    CreateNavButtons(Layout.Nav_Security);

                }
                break;
        }

        foreach(NavButton o in m_NavButtons)
        {
            m_CtrlButtons.Add(o.ctrl);
        }
        return m_CtrlButtons;
    }


    private UserGroup GetUserGroup(string UserName, string Password)
    {
        //Fake check. in fact the information will be compare with database' data.
      
        //Data component will search the staff in staff table
        //and also search in the administror table

        UserGroup curGroup = (UserGroup)StaffDB.Singleton().GetUserGroup(UserName, Password);
        //UserGroup curGroup = UserGroup.Guest;
        //if(UserName == "admin")
        //{
        //    curGroup = UserGroup.Admin;
        //}
        //if(UserName == "manager")
        //{
        //    curGroup = UserGroup.Manager;
        //}
        //if(UserName == "lead")
        //{
        //    curGroup = UserGroup.Lead;
        //}
        //if(UserName == "staff")
        //{
        //    curGroup = UserGroup.Staff;
        //}
        //if (UserName == "assistant")
        //{
        //    curGroup = UserGroup.Assitant;
        //}
        //if (UserName == "safety")
        //{
        //    curGroup = UserGroup.Safety;
        //}
        return curGroup ;
    }

    //Check if current user exist, otherwise redirect to login page
    public void CheckUserSession()
    {
        if(m_MainPage.Session[m_Usgkey] == null 
           || (UserGroup)m_MainPage.Session[m_Usgkey] == UserGroup.Guest)
         {
             m_MainPage.Response.Redirect("LoginPage.aspx");
        }
        else 
        {
            // update sessions if needed, because different user have different session state
            // Change current navigation button by query string
            if (m_MainPage.Request.QueryString["NavButton"] != null)
            {
                //Get button name by query string;
                m_MainPage.Session[m_NavKey] = m_MainPage.Request.QueryString["NavButton"];

            }
            else
            {
                m_MainPage.Session[m_NavKey] = null;
            }
           

        }
    }
    //Validate User according to the database information 
    //and then refresh page according the userGroup . 
    public bool ValidateUser(string UserName,string Password)
    {
        bool IsOk = false;
        m_MainPage.Session[Engine.m_Usgkey] = GetUserGroup(UserName,Password);
        IsOk = (UserGroup)m_MainPage.Session[Engine.m_Usgkey] == UserGroup.Guest ? false : true;
        if(IsOk)
        {
            //Update session
            //Save user name
            m_MainPage.Session[m_Usnkey] = UserName;
        }
        return IsOk;
    }

    //handle message
    private void MainProcess()
    {

    }

#region static functions
    static public string GetSumExcelPath()
    {
        return "ok";
    }
#endregion
 #region members
    Page m_MainPage = null;
    ArrayList m_NavButtons = new ArrayList();
    ArrayList m_ContentCtrlNames = new ArrayList(); // This Content name list is corresponding with navigation bottons.
    SortedList m_ButtonCmdList = new SortedList();
    ArrayList m_CtrlButtons = new ArrayList();
#endregion
    
  
#region static member 
        static public string m_Usskey = "Uss"; //User status session key
        static public string m_Usgkey = "Usg"; //User group session key 
        static public string m_Usnkey = "Usn";  //User name
        static public string m_NavKey = "Nav";  //Current Navigation control Name
        
        
#endregion
    }


